<template>
	<view class="dutys_box">
		<AdBanner width="100%" diyStyle="margin:-20rpx 0rpx 0rpx 0rpx"/>
		<view class="choose">
			<uni-segmented-control 
				:current="nowWeekTypeIndex" 
				:values="items" 
				style-type="button"
				:active-color="primary_hot_color" 
				@clickItem="onChooseFun" />
		</view>
		<view class="fill_by_btn" v-if="dutys[nowWeekTypeIndex].length">
			<MySteps :color="stepColor(item.duty[0])" :active="item.duty[0].week === nowWeek" v-for="item in dutys[nowWeekTypeIndex]" :key="item.id">
				<view class="duty_card">
					<DutyCard 
						@isDeleteDutyModelEmit="isDeleteDutyModelFun"
						@addModelDuthByAdminEmit="openAddDutyModelFun"
						@deleteDutyByAdminEdmit="isDeleteDutyByDayEdmit"
						:fillInfo="item.duty[0].week === nowWeek && nowDormitoryWeekType===nowWeekTypeIndex ? '今天值日' : ''"
						:dutyData="item.duty"
						:isAdminEdit="true"
						/>
				</view>
			</MySteps>			
		</view>
		<view v-if="!dutys[nowWeekTypeIndex].length">
			<view class="null_duty_data">
				没有值日的
			</view>
			<MyNull img="nullDuty.png" />
		</view>
		<view class="footer_btn_admin" >
			<MyButton fontSize="28rpx" :borderColor="primary_hot_color" padding="0rpx" :bgc="primary_hot_color" :clickFun="()=>modelFillDutyFlag=Math.random()">填充{{nowWeekTypeIndex===WeekType.SIGLE ? '单周' : '双周'}}轮流值日</MyButton>
			<MyButton fontSize="28rpx" padding="0rpx" :bgc="primary_light_color" :clickFun="()=>modelSaveDutyFlag=Math.random()">保存所有{{nowWeekTypeIndex===WeekType.SIGLE ? '单周' : '双周'}}值日</MyButton>
		</view>
		<uni-popup ref="addDutyModelRef" background-color="#fff" >
			<view class="popup_content">
				<view class="title" v-if="chooseDayItem?.week !== undefined">
					安排到：
					<view style="display: flex; align-items: center;" @click="()=>modalIsEditDayFlag=Math.random()">
						{{changeWeekByNum(chooseDayItem.week)}} {{chooseDayItem.time.replace(':00.000000','')}}
						<!-- <MyIcons size="30rpx" :src="joinSystemPath('setBlock.png')"/> -->
						<view :style="`color: ${primary_hot_color};margin-left:6rpx;`">
							修改
						</view>
					</view>
				</view>
				<viwe class="choose_box">
					<view 
						@click="clickUserFun(userItem)" 
						v-for="userItem in allJoinerData" 
						:key="userItem.user_id" 
						class="item_user text_ellipsis"
						:style="`border:1px solid ${userIsChoosedFun(userItem) ? primary_hot_color : primary_text_color}`"
					>
						<viwe>
							<Avatar :fileName="userItem.user_avatar" size="70rpx" />
						</viwe>
						<view class="user_name text_ellipsis">{{userItem.nick_name_by_dormitory}}</view>
					</view>
				</viwe>
			</view>
		</uni-popup>
		<MyModal :openModalFlag="modelDeleteDutyFlag" :okFun="()=>deleteDutyByAdminEdmitFun(catchDeleteDutyObj?.item,catchDeleteDutyObj?.isDeleteAll)">
			<template #title>
				确定删除该天下的所有值日吗？
			</template>
			<template #content>
				<TipInfo :color="shallow_text_color" id="11"></TipInfo>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modelFillDutyFlag" :okFun="fillDutyUsers">
			<template #title>
				确定填充{{nowWeekTypeIndex===WeekType.SIGLE ? '单周' : '双周'}}的所有空缺值日吗？
			</template>
			<template #content>
				<TipInfo :color="shallow_text_color" id="10"></TipInfo>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modelSaveDutyFlag" :okFun="isSaveAllDuty">
			<template #title>
				确定保存{{nowWeekTypeIndex===WeekType.SIGLE ? '单周' : '双周'}}的值日吗？
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalIsEditDayFlag">
			<template #title>
				修改时间安排
			</template>
			<template #content>
				<EditorDuty :formData="chooseDayItem" @changeEditDutyDataEmit="changeEditDutyTimeDataFun" />
			</template>
			<template #okCancelBtn>
				<MyButton 
					:bgc="primary_hot_color" 
					width="500rpx"
					:clickFun="closeEditDayModelFun"
				>关闭</MyButton>
			</template>
		</MyModal>
		<Tips />
	</view>
</template>

<script setup>
	import {
		onShow,
		onLoad,
		onHide
	} from '@dcloudio/uni-app'
	import {
		ref,
		computed,
		nextTick,
		onUnmounted,
		watchEffect
	} from 'vue'

	import MySteps from '@/components/MySteps/MySteps.vue'
	import DutyCard from '@/components/Dormitory/DutyCard/DutyCard.vue'
	import EditorDuty from '@/components/Dormitory/EditorDuty/EditorDuty.vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyNull from '@/components/MyNull/MyNull.vue'
	import ClockNoN from '@/components/Dormitory/ClockNoN/ClockNoN.vue'
	import MyIcons from '@/components/MyIcons/MyIcons.vue'
	import MyModal from '@/components/MyModal/MyModal.vue'
	import MyButton from '@/components/MyButton/MyButton.vue'
	import TipInfo from '@/components/TipInfo/TipInfo.vue'
	import AdBanner from '@/components/AdBanner/AdBanner.vue'

	import {
		dynamicStyleStore
	} from '@/stores/dynamicStyle.js'
	import {
		userStore
	} from '@/stores/user'

	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	
	import {
		changeWeekByNum
	} from '@/utils/changeData.js'

	import {
		deleteStrByPatten,
		getNowWeek
	} from '@/utils/changeData.js'
	import {
		openMessageAuth
	} from '@/utils/messageAuth.js'
	import {
		joinSystemPath
	} from '@/utils/imgJoinName.js'

	import {
		verifyIsLogin,
		verifyFormData
	} from '@/hooks/verify.js'
	import MyItemVue from '../../../components/MyItem/MyItem.vue'
	import moment from 'moment'
	
	import { 
		DefaultPhone,
		DutyAddType,
		WeekType
	} from '../../../enum/GlobalEnum'

	const user_store = userStore()

	const dynamicStyle_store = dynamicStyleStore()
	const dormitoryModel = new DormitoryModel()

	const {
		primary_hot_color,
		primary_light_color,
		shallow_text_color,
		primary_main_bgc,
		primary_text_color
	} = dynamicStyle_store.dormitoryStyle
	

	const formData = ref({
		limit: 1000,
		page: 0,
		orderBy: 'time.desc',
		week: '8',
		time: '99:99',
	})
	const items = ref(['单周','双周'])
	
	const addDutyModelRef= ref()

	const dormitoryId = ref(uni.getStorageSync('homeData').dormitory_id)
	
	const noBindPhone = computed(()=>user_store.userInfo.phone === DefaultPhone)
	const isAdmin = computed(()=>user_store.userInfo.user_id === dormiotryAdmin.value)
	const isPrivacy = computed(()=>user_store.userInfo.isPrivacy)

	const dutys = ref([[],[]])
	const nowWeek = ref(0)
	const dormiotryAdmin = ref('')
	const allJoinerData = ref([])
	const modalIsEditDayFlag = ref(0)
	const modelFillDutyFlag = ref(0)
	const modelDeleteDutyFlag = ref(0)
	const modelSaveDutyFlag=ref(0)
	const nowWeekTypeIndex = ref(0)
	const nowDormitoryWeekType = ref(0)
	
	//安排到什么时间
	const chooseDayItem = ref()
	//当前选中时间的值日生
	const chooseUsersData = ref([])
	
	const closeEditDayModelFun=()=>{
		modalIsEditDayFlag.value = -Math.random()
	}
	
	//是否保存所有值日
	const isSaveAllDuty=async()=>{
		uni.$emit('checkUserPrivacyProtocol')
		if(!isPrivacy.value){
			return
		}
		// if(noBindPhone.value){
		// 	uni.$emit('openPhonePopubFlag',false,false,'平台需要能通知宿舍长每天未值日的室友')
		// 	return
		// }
		if(isKongDuty.value){
			uni.$emit('tips','存在没有填完的值日，请先填完或者删除','warn')
			return
		}
		const _dutys = JSON.parse(JSON.stringify(dutys.value[nowWeekTypeIndex.value]))
		_dutys.forEach(item=>{
			item.duty.forEach(item2=>{
				delete item2.joinBgc
				delete item2.clocked
				delete item2.createAt
				delete item2.nick_name_by_dormitory
				delete item2.updateAt
				delete item2.dormitory_id
				delete item2.admin_id
				item2.dutyWeekType = nowWeekTypeIndex.value
			})
			item.duty.shift()
		})
		console.log('保存',_dutys)
		const {data,success} = await dormitoryModel.postSaveDutysByAdmin({data:_dutys,dutyWeekType:nowWeekTypeIndex.value},dormitoryId.value)
		if(success){
			uni.$emit('tips',data,'success')
			modelSaveDutyFlag.value = -Math.random()
		}
	}
	
	const onChooseFun=(e)=>{
		nowWeekTypeIndex.value = e.currentIndex
	}
	
	//是否删除值日
	const catchDeleteDutyObj = ref({})
	const isDeleteDutyByDayEdmit = (item,isDeleteAll)=>{
		if(isDeleteAll){
			catchDeleteDutyObj.value={item,isDeleteAll}
			modelDeleteDutyFlag.value = Math.random()
		}else{
			deleteDutyByAdminEdmitFun(item,isDeleteAll)
		}
	}
	
	const deleteDutyByAdminEdmitFun=(item,isDeleteAll)=>{
		let deleteDutyIndex = null
		for(let i=0;i<dutys.value[nowWeekTypeIndex.value].length;i++){
			const tmp = dutys.value[nowWeekTypeIndex.value][i].duty
			for(let j=0;j<tmp.length;j++){
				if(tmp[j].user_id === item.user_id && tmp[j].week === item.week && tmp[j].time === item.time){
					if(isDeleteAll){
						deleteDutyIndex=i
						break
					}
					tmp.splice(j,1)
					dutys.value[nowWeekTypeIndex.value][i] = {duty:tmp}
					break
				}
			}
		}
		if(deleteDutyIndex!==null){
			dutys.value[nowWeekTypeIndex.value].splice(deleteDutyIndex,1)
		}else{
			uni.$emit('tips','保存后，该值日的所有打卡数据将全部删除','info',2000)
		}
	}
	
	const isKongDuty = computed(()=>dutys.value[nowWeekTypeIndex.value].filter(item=>item.duty.length===1).length)
	
	watchEffect(()=>{
		if(!dutys.value[nowWeekTypeIndex.value]?.length || !chooseDayItem.value) return
		console.log('测试',dutys.value[nowWeekTypeIndex.value])
		const tmp = [
			...dutys.value[nowWeekTypeIndex.value].filter(item=>
			item.duty[0].week === chooseDayItem.value.week
			&& item.duty[0].time === chooseDayItem.value.time
			)[0]?.duty || []]
		tmp.shift()
		chooseUsersData.value = tmp
	});
	const userIsChoosedFun=(user)=>{
		const {week,time} = chooseDayItem.value
		const flagDutys = dutys.value[nowWeekTypeIndex.value].filter(item=>item.duty[0].week === week && item.duty[0].time === time)
		return flagDutys[0]?.duty?.filter(item=>item?.user_id===user.user_id)?.length
	}
	const changeEditDutyTimeDataFun=(e)=>{
		e.time = e.time.split(':')[0]+':00'
		chooseDayItem.value = {
			time:(e.time || chooseDayItem.value.time).replace(':00.000000',''),
			week:parseInt(e.week) + 1 || chooseDayItem.value.week
		}
		uni.$emit('tips','修改成功，别忘了点击室友头像进行选择哦','success',2000)
	}
	
	//步骤条颜色
	const stepColor = (item) => {
		let color = ''
		if (item.week > nowWeek.value) {
			color = shallow_text_color
		} else if (item.week < nowWeek.value) {
			color = primary_light_color
		} else {
			color = primary_hot_color
		}
		return color
	}
	
	const verifyShowAutoRefreshBtnFun=(data)=>{
		for(let i=0;i<data.length;i++){
			const dutysItem=data[i].duty
			for(let j=0;j<dutysItem.length;j++){
				const {addType} = dutysItem[j]
				if(addType === DutyAddType.NO_SELF_ADD){
					nextTick(()=>{
						isHaveFillDuty.value = true
					})
				}
			}
		}
	}
	
	const getDutys = async (weekType) => {
		const {
			data,
			success
		} = await dormitoryModel.getDutys({
			...formData.value,
			weekType
		}, dormitoryId.value)
		if (success) {
			const weekFlag = [1,2,3,4,5,6,7]
			data.forEach(item => {
				item.duty[0].time = deleteStrByPatten(item.duty[0].time, /:\d{2}.\d{6}/)
			})
			nowWeek.value = getNowWeek()
			for(let i=0;i<data.length;i++){
				const dutysItem=data[i].duty
				const index = weekFlag.findIndex(item=>item === dutysItem[0].week)
				if(index !== -1){
					weekFlag.splice(index,1)
				}
				dutysItem.unshift({
					"id": "admin_add",
					"time": dutysItem[0].time,
					"week": dutysItem[0].week,
					"addType": dutysItem[0].addType,
					"clocked": null,
					"user_avatar": "addUser.png",
				})
			}
			weekFlag.forEach(week=>{
				const tmpDuty = {
					"id": "admin_add",
					"time": '09:00',
					"week": week,
					"addType": DutyAddType.SELF_ADD,
					"clocked": null,
					"user_avatar": "addUser.png",
				}
				data.push({
					duty:[tmpDuty]
				})
			})
			data.sort((a,b)=>a.duty[0].week - b.duty[0].week)
			// if(!dutys.value[0].length && !dutys.value[1].length){
			// 	dutys.value = []
			// }
			nextTick(()=>{
				dutys.value[weekType]=data
			})
		}
	}

	const modalType = ref('添加')
	//添加修改值日
	const modalIsEditDutyFlag = ref(0)
	const modalIsDeleteDutyFlag = ref(0)
	const modalGoClockFlag=ref(0)
	const modalIdAutoRefreshDutyFlag = ref(0)
	const modalIdDeleteAllFillDutyFlag=ref(0)
	const addDutyModelFlag = ref(0)
	const editDutyFormData = ref({
		time: '09:00',
		week: 1
	})
	const editDutyFormDataSchema = {
		time: {
			required: true,
			tip: '时间'
		}
	}
	//添加值日
	const openEditDuty = () => {
		editDutyFormData.value = {
			time: '09:00',
			week: 1
		}
		modalType.value = '添加'
		modalIsEditDutyFlag.value = Math.random()
	}
	
	
	
	const clickUserFun=(data)=>{
		const tmp = chooseUsersData.value.filter(item=>item.user_id === data.user_id && item.addType === DutyAddType.SELF_ADD)
		if(tmp.length){
			uni.$emit('tips','ta在该时间下已有值日了','error',1000)
			return
		}
		console.log('星期',chooseDayItem.value)
		const {week,time} = chooseDayItem.value
		console.log('目标',data)
		console.log('全部',dutys.value[nowWeekTypeIndex.value])
		const tmpDutys=JSON.parse(JSON.stringify(dutys.value[nowWeekTypeIndex.value]))
		let isPushFlag=false
		tmpDutys.forEach(item=>{
			//找到插入时间
			if(item.duty[0].week===week && item.duty[0].time === time){
				isPushFlag=true
				//清除该时间下的轮流值日
				if(item.duty[0].addType === DutyAddType.NO_SELF_ADD){
					item.duty.splice(1,item.duty.length)
				}
				item.duty[0].addType = DutyAddType.SELF_ADD
				item.duty.push({
					...data,
					week,
					time,
					addType:DutyAddType.SELF_ADD
				})
			}
		})
		if(!isPushFlag){
			const duty = [
				{
					...data,
					week,
					time,
					addType:DutyAddType.SELF_ADD
				}
			]
			duty.unshift({
				"id": "admin_add",
				"time": time,
				"week": week,
				"addType": DutyAddType.SELF_ADD,
				"clocked": null,
				"user_avatar": "addUser.png",
			})
			tmpDutys.push({duty})
			tmpDutys.sort((a,b)=>a.duty[0].week - b.duty[0].week)
		}
		dutys.value[nowWeekTypeIndex.value] = tmpDutys
		addDutyModelRef.value.close()
		uni.$emit('tips','选择成功','success')
	}
	
	//打开管理选择值日生的弹窗
	const openAddDutyModelFun=async(addDay,dutyData)=>{
		console.log('点击',addDay,dutyData)
		chooseUsersData.value = dutyData
		chooseDayItem.value = {
			...addDay,
			time:addDay.time.replace('.000000','')
		}
		addDutyModelRef.value.open('right')
		const {
			data,
			success
		} = await dormitoryModel.getAllJoiner({
			limit:1000,
			page: 0,
			orderBy: 'createAt.asc'
		}, dormitoryId.value)
		if(success){
			console.log('全体',data)
			allJoinerData.value = data
		}
	}
	
	//一键填充轮流值日
	const fillDutyUsers=async()=>{
		uni.showLoading({
			mask:true
		})
		const {data,success} = await dormitoryModel.getFillDutyUsers({},dormitoryId.value)
		if(success){
			//池子
			let fillUsers = []
			for(let i=0;i<7;i++){
				fillUsers = [...fillUsers,...data]
			}
			let isPushFlag=false
			//获取空位置
			dutys.value[nowWeekTypeIndex.value].forEach((item,index)=>{
				if(item.duty?.length === 1){
					isPushFlag=true
					const {
						user_id,
						user_avatar,
						nick_name_by_dormitory
					} = fillUsers.shift()
					const {
						week,
						time,
					} = item.duty[0]
					dutys.value[nowWeekTypeIndex.value][index].duty[0].addType = DutyAddType.NO_SELF_ADD
					dutys.value[nowWeekTypeIndex.value][index].duty[1] = {
						user_id,
						user_avatar,
						nick_name_by_dormitory,
						week,
						time,
						addType:DutyAddType.NO_SELF_ADD
					}
				}
			})
			uni.hideLoading()
			isPushFlag
			?uni.showToast({
				icon:success,
				title:'填充成功',
				duration:700
			})
			:uni.$emit('tips','没有空缺值日,不需要填充','warn')
		}else{
			uni.hideLoading()
		}
	}

	//验证是否操作的自己的值日
	const verifyIsMyDuty = (item) => {
		if (item.user_id !== user_store.userInfo.id) {
			const tip = '请不要操作别人的值日'
			uni.$emit('tips', tip, 'warn')
			throw new Error(tip)
		}
	}

	//是否删除值日
	const isDeleteDutyModelFun = (item) => {
		verifyIsMyDuty(item)
		editDutyData.value = item
		modalIsDeleteDutyFlag.value = Math.random()
	}

	onShow(() => {
		nextTick(()=>{
			getDutys(WeekType.SIGLE)
			getDutys(WeekType.DOUBLE)
		})
	})
	
	onLoad((opt)=>{
		const {dormitory_id,chooseWeekType:_chooseWeekType,nowDormitoryWeekType:_nowDormitoryWeekType}=opt
		if(dormitory_id){
			dormitoryId.value=dormitory_id
		}
		nowWeekTypeIndex.value = Number(_chooseWeekType)
		nowDormitoryWeekType.value = Number(_nowDormitoryWeekType)
		nextTick(()=>{
			uni.$emit('checkUserPrivacyProtocol')
		})
	})
</script>

<style lang="less">
	.text_ellipsis{
		white-space:nowrap;
		text-overflow:ellipsis;
		overflow: hidden;
	}
	.duty_card{
		position: relative;
	}
	.popup_content {
		padding: 20rpx;
		background-color: #fff;
		width: 400rpx;
		color: v-bind(primary_text_color);
		box-sizing: border-box;
		.title{
			width: 100%;
			margin-bottom: 20rpx;
			font-size: 30rpx;
			display: flex;
		}
		.choose_box{
			display: grid;
			grid-template-columns: 1fr 1fr;
			gap: 8rpx;
			width: 100%;
			.item_user{
				display: flex;
				justify-content: center;
				align-items: center;
				flex-wrap: wrap;
				padding: 10rpx 5rpx;
				border: 2rpx solid v-bind(primary_text_color);
				border-radius: 10rpx;
				.user_name{
					text-align: center;
					font-size: 24rpx;
					margin-top: 5rpx;
					padding: 0 4rpx;
					width: 100%;
				}
			}
		}
	}
	.modal_info{
		color: v-bind(primary_text_color);
		font-size: 28rpx;
	}
	.dutys_box {
		min-height: calc(100vh);
		padding: 20rpx;
		background-color: v-bind(primary_main_bgc);
		.choose{
			padding-top: 20rpx;
			background-color: v-bind(primary_main_bgc);
			z-index: 2;
		}
		.uni-badge--x {
			display: block !important;
			position: relative;
		}
		.null_duty_data {
			display: flex;
			justify-content: center;
			color: v-bind(primary_hot_color);
		}
		.fill_by_btn{
			padding-bottom: 150rpx;
		}

		.add_duty {
			width: 130rpx;
			height: 130rpx;
			position: fixed;
			bottom: 100rpx;
			right: 50rpx;
			z-index: 10;
			background-color: v-bind(primary_hot_color);
			border-radius: 100rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	.footer_btn_admin{
		display: grid;
		grid-template-columns: 1fr 1fr;
		column-gap: 20rpx;
		width: 95%;
		position: fixed;
		left: 50%;
		transform: translate(-50%,0);
		bottom: 0rpx;
		background-color: #FFFFFF;
		padding-bottom: 50rpx;
	}
</style>
